/**
 * User: alesj
 * Date: 2005.6.8
 * Time: 11:20:35
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.ecos.page;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import java.util.*;

public class AlphaHelper {

    private static final Log logger = LogFactory.getLog(AlphaHelper.class);
    private static Map instanceMap = new TreeMap();

    private Map alphaListMap = new HashMap();
    private char[] chars;

    private AlphaHelper(char[] chars) {
        this.chars = chars;
    }

    public synchronized static AlphaHelper getInstance(char[] chars) {
        CharsKey ck = new CharsKey(chars);
        AlphaHelper alphaHelper = (AlphaHelper)instanceMap.get(ck);
        if (alphaHelper == null) {
            alphaHelper = new AlphaHelper(chars);
            instanceMap.put(ck, alphaHelper);
        }
        return alphaHelper;
    }

    private List buildAlphaList(int totalLenght) {
        List alphaList = new ArrayList();
        buildString(totalLenght, null, 0, alphaList);
        if (totalLenght > 2) {
            logger.warn("Building alphaList with length " + totalLenght + ".");
        } else {
            alphaListMap.put(new Integer(totalLenght), alphaList);
        }
        return alphaList;
    }

    private void buildString(int length, String previous, int counter, List alphaList) {
        if (length > 0) {
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                StringBuffer buffer;
                if (previous == null) {
                    buffer = new StringBuffer().append(c);
                } else {
                    buffer = new StringBuffer(previous).append(c);
                }
                char[] charArray = buffer.toString().toCharArray();
                alphaList.add(charArray);
                buildString(length - 1, buffer.toString(), counter + 1, alphaList);
            }
        }
    }

    private List getAlphaList(int totalLenght) {
        List alphaList = (List)alphaListMap.get(new Integer(totalLenght));
        if (alphaList == null) {
            alphaList = buildAlphaList(totalLenght);
        }
        return alphaList;
    }

    public int getSize(int totalLenght) {
        return getAlphaList(totalLenght).size();
    }

    public char[] getChars(int index, int totalLenght) {
        List alphaList = getAlphaList(totalLenght);
        return (char[])alphaList.get(index);
    }

}
